#include"threadPool.h"
#include "detachCommand.h"
#include "database.h"

int tidArrInit(tidArr_t* ptidArr,int workerNum){
    ptidArr->arr = (pthread_t *)calloc(workerNum,sizeof(pthread_t));
    ptidArr->workerNum = workerNum;
    return 0;
}

int threadPoolInit(threadPool_t *pthreadPool,int workerNum){
    bzero(pthreadPool,sizeof(threadPool_t));
    tidArrInit(&pthreadPool->tidArr,workerNum);
    taskQueueInit(&pthreadPool->taskQueue);
    pthread_mutex_init(&pthreadPool->mutex,NULL);
    pthread_cond_init(&pthreadPool->cond,NULL);
    return 0;
}

void unlock(void* arg){ // 包装函数
    threadPool_t* pthreadPool = (threadPool_t *)arg;
    printf("unlock!\n");
    pthread_mutex_unlock(&pthreadPool->mutex);
}

void* threadFunc(void* arg){
    threadPool_t* pthreadPool =(threadPool_t *)arg;
    
    //连接数据库
    pthread_mutex_lock(&pthreadPool->mutex);
    MYSQL* mysql;
    mysql = mysql_init(NULL);
    connectMySQL(mysql);
    pthread_mutex_unlock(&pthreadPool->mutex);
    
    // 子线程,消费者
    while(1){
        pthread_mutex_lock(&pthreadPool->mutex); //加锁
        //pthread_cleanup_push(unlock,pthreadPool); //压栈
        while(pthreadPool->taskQueue.queueSize <= 0&&pthreadPool->exitFlag ==0){
            pthread_cond_wait(&pthreadPool->cond,&pthreadPool->mutex);
        }
        if(pthreadPool->exitFlag == 1){
                printf("I am child,I am going to exit!\n");
                pthread_mutex_unlock(&pthreadPool->mutex);
                pthread_exit(NULL);
        }
        //队列不为空
        task_t *ptask = (task_t*)calloc(1,sizeof(task_t));
        deQueue(&pthreadPool->taskQueue,ptask);
        printf("I am worker,I got a netfd = %d\n",ptask->netfd);
        pthread_mutex_unlock(&pthreadPool->mutex);
        //pthread_cleanup_pop(1);                 //弹栈
        
        // 执行业务
        business(ptask,mysql);

        //释放资源
        close(ptask->netfd);
        free(ptask);
    }
    //关闭数据连接
    mysql_close(mysql);
}

int makeWorker(threadPool_t *pthreadPool){
    for(int i=0;i<pthreadPool->tidArr.workerNum;++i){
        pthread_create(&pthreadPool->tidArr.arr[i],NULL,threadFunc,pthreadPool);
    }
    return 0;
}
